package AgentTravel.Behaviours;

import java.util.HashMap;
import java.util.Map;

import AgentTravel.HostAgent;
import AgentTravel.MyOntology;
import AgentTravel.VisitorAgent;
import AgentTravel.LogicObjects.User;
import AgentTravel.LogicObjects.UserInfoForServer;
import AgentTravel.Messages.RegisterMessage;
import AgentTravel.Messages.ServerConfirmationInfo;
import AgentTravel.Messages.UnsubscribeMessage;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;

public class ServerGetUnsubscribeBehaviour extends CyclicBehaviour 
{

	private Map<String,UserInfoForServer> users;
	private Map<String,String> passLogin;
	private Map<String,AID> userGui;
	
	public ServerGetUnsubscribeBehaviour(Map<String, UserInfoForServer> users2,Map<String, String> passLogin2,Map <String,AID> userGui)
	{
		this.users=users2;
		this.passLogin=passLogin2;
		this.userGui=userGui;
	}
	
	@Override
	public void action() 
	{
		MessageTemplate mt=MessageTemplate.MatchPerformative(ACLMessage.CANCEL);
		
		ACLMessage msg = myAgent.receive(mt);
		
		if (msg != null) 
		{
			UnsubscribeMessage msgObj=null;
		
			try
			{
				msgObj=(UnsubscribeMessage)msg.getContentObject();
			}
			catch(UnreadableException ex)
			{
				System.out.println("UUUUnreadable :(");
			}
			
			
			if(msgObj!=null)
			{
				System.out.println("SERWER: Dostalem prosbe o unsubscribe");
				if(!users.containsKey(msgObj.UserName) || !passLogin.get(msgObj.UserName).equals(msgObj.Password))
				{
					//odrzucenie
					ACLMessage reply=new ACLMessage(ACLMessage.DISCONFIRM);
					reply.addReceiver(msg.getSender());
					myAgent.send(reply);
				}
				else
				{			
					UserInfoForServer uifs=users.get(msgObj.UserName);
					
					ACLMessage killMsg=new ACLMessage(ACLMessage.INFORM);
					try 
					{
						killMsg.addReceiver(new AID(uifs.yourHostAgent.getName(),true));
						killMsg.addReceiver(new AID(uifs.yourVisitorAgent.getName(),true));
						killMsg.setContent(MyOntology.killText);
						myAgent.send(killMsg);
					} 
					catch (StaleProxyException e1) 
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					users.remove(msgObj.UserName);
					passLogin.remove(msgObj.UserName);
					userGui.remove(msgObj.UserName);
										
					//zaakceptowanie
					ACLMessage reply=new ACLMessage(ACLMessage.CONFIRM);
					reply.addReceiver(msg.getSender());
					myAgent.send(reply);
				}
			}
			else	
			{
				System.out.println("Nie ma tu zadnego obiektu");
			}
			
			
		}
		else 
		{
			block();
		}
		
	}

}
